package com.ctcemti.mdm.common.util;

import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
/* *
 * @Author bxf
 * @Description 异常消息信息打印项
 * @Date 11:17 2020/3/4
 * @param null
 * @return 
 */
public class ExceptionStackTrace {
    public static String getExceptionStackTrace(Throwable anexcepObj){
        StringWriter sw = null;
        PrintWriter printWriter = null;
        try{
            if(anexcepObj != null)
            {
                sw = new StringWriter();
                printWriter = new PrintWriter(sw);
                anexcepObj.printStackTrace(printWriter);
                printWriter.flush();
                sw.flush();
                return sw.toString();
            }
            else
                return null;
        }finally
        {

            try
            {
                if(sw != null)
                    sw.close();
                if(printWriter != null)
                    printWriter.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取exception的详细错误信息。
     */
    public static String getExceptionMessage(Throwable e)
    {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        String str = sw.toString();
        return str;
    }

    public static String getRootErrorMseeage(Exception e)
    {
        Throwable root = ExceptionUtils.getRootCause(e);
        root = (root == null ? e : root);
        if (root == null)
        {
            return "";
        }
        String msg = root.getMessage();
        if (msg == null)
        {
            return "null";
        }
        return StringUtils.defaultString(msg);
    }

}
